<template>
  <div class="car-list">
    <!-- 搜索表单 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item>
          <el-input v-model="searchForm.carName" placeholder="请输入车名" clearable></el-input>
        </el-form-item>
        <el-form-item>
          <el-select v-model="searchForm.status" placeholder="车辆状态" clearable>
            <el-option label="可租" :value="1"></el-option>
            <el-option label="已租" :value="0"></el-option>
            <el-option label="下架" :value="-1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <i class="el-icon-search"></i> 搜索
          </el-button>
          <el-button @click="resetSearch">
            <i class="el-icon-refresh"></i> 重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮 -->
    <el-card class="table-card">
      <div class="operation-bar">
        <el-button type="primary" @click="handleAdd">
          <i class="el-icon-plus"></i> 新增车辆
        </el-button>
        <el-button 
          type="danger" 
          @click="handleBatchStatusChange(-1)" 
          :disabled="!selectedCars.length"
        >
          <i class="el-icon-download"></i> 批量下架
        </el-button>
        <el-button 
          type="success" 
          @click="handleBatchStatusChange(1)" 
          :disabled="!selectedCars.length"
        >
          <i class="el-icon-upload2"></i> 批量上架
        </el-button>
      </div>

      <!-- 车辆表格 -->
      <el-table
        :data="paginatedData"
        border
        @selection-change="handleSelectionChange"
        v-loading="loading"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column label="编号" type="index" width="80"></el-table-column>
        <el-table-column prop="cname" label="车名" width="180"></el-table-column>
        <el-table-column prop="cinfo" label="车辆信息"></el-table-column>
        <el-table-column prop="crent" label="租金/天" width="120">
          <template v-slot="{ row }">
            ¥{{ row.crent }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template v-slot="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template v-slot="{ row }">
            <el-button
              :type="row.status === 1 ? 'warning' : 'success'"
              size="mini"
              @click="handleStatusChange(row)"
              :disabled="row.status === 0"
            >
              {{ row.status === 1 ? '下架' : '上架' }}
            </el-button>
            <el-button
              type="primary"
              size="mini"
              @click="handleEdit(row)"
            >
              编辑
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pagination.currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pagination.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalData"
        >
        </el-pagination>
      </div>
    </el-card>

    <!-- 新增/编辑车辆对话框 -->
    <car-add
      :visible.sync="addDialogVisible"
      :car="currentCar"
      @success="handleAddSuccess"
    />
  </div>
</template>

<script>
import CarAdd from './CarAdd.vue'
import request from '@/utils/request'

export default {
  name: 'CarList',
  
  components: {
    CarAdd
  },

  data() {
    return {
      // 搜索表单
      searchForm: {
        carName: '',
        status: ''
      },
      // 表格数据
      tableData: [],
      loading: false,
      selectedCars: [],
      // 新增对话框
      addDialogVisible: false,
      // 当前编辑的车辆
      currentCar: null,
      // 分页
      pagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      }
    }
  },

  created() {
    this.fetchData()
  },

  computed: {
    // 计算分页后的数据
    paginatedData() {
      const start = (this.pagination.currentPage - 1) * this.pagination.pageSize
      const end = start + this.pagination.pageSize
      return this.filteredData.slice(start, end)
    },

    // 计算筛选后的数据
    filteredData() {
      let result = [...this.tableData]
      
      // 根据车名筛选
      if (this.searchForm.carName) {
        const keyword = this.searchForm.carName.toLowerCase()
        result = result.filter(item => 
          item.cname.toLowerCase().includes(keyword)
        )
      }
      
      // 根据状态筛选
      if (this.searchForm.status !== '') {
        result = result.filter(item => 
          item.status === this.searchForm.status
        )
      }
      
      return result
    },

    // 计算总数据量
    totalData() {
      return this.filteredData.length
    }
  },

  methods: {
    // 获取车辆列表
    async fetchData() {
      this.loading = true
      try {
        const res = await request.get('/car/list')
        if (res.code === 0) {
          this.tableData = res.data
        } else {
          this.$message.error(res.msg || '获取车辆列表失败')
        }
      } catch (error) {
        console.error('获取车辆列表失败:', error)
        this.$message.error('获取车辆列表失败')
      }
      this.loading = false
    },

    // 获取状态类型
    getStatusType(status) {
      switch (status) {
        case 1: return 'success'
        case 0: return 'warning'
        case -1: return 'info'
        default: return ''
      }
    },

    // 获取状态文本
    getStatusText(status) {
      switch (status) {
        case 1: return '可租'
        case 0: return '已租'
        case -1: return '下架'
        default: return '未知'
      }
    },

    // 搜索
    handleSearch() {
      this.pagination.currentPage = 1 // 重置到第一页
    },

    // 重置搜索
    resetSearch() {
      this.searchForm = {
        carName: '',
        status: ''
      }
      this.pagination.currentPage = 1 // 重置到第一页
    },

    // 表格选择
    handleSelectionChange(selection) {
      this.selectedCars = selection
    },

    // 新增车辆
    handleAdd() {
      this.currentCar = null
      this.addDialogVisible = true
    },

    // 新增成功回调
    handleAddSuccess() {
      this.$message.success('添加成功')
      this.fetchData()
    },

    // 编辑车辆
    async handleEdit(row) {
      this.currentCar = { ...row }
      this.addDialogVisible = true
    },

    // 更改单个车辆状态
    async handleStatusChange(row) {
      const newStatus = row.status === 1 ? -1 : 1
      const actionText = newStatus === 1 ? '上架' : '下架'
      
      try {
        await this.$confirm(`确认要${actionText}该车辆吗？`, '提示', {
          type: 'warning'
        })
        
        const res = await request.get('/CarStatusServlet', {
          params: {
            cid: row.cid,
            status: newStatus
          }
        })
        
        if (res.code === 0) {
          row.status = newStatus
          this.$message.success(`${actionText}成功`)
        } else {
          this.$message.error(res.msg || `${actionText}失败`)
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error(`${actionText}失败:`, error)
          this.$message.error(`${actionText}失败`)
        }
      }
    },

    // 批量更改状态
    async handleBatchStatusChange(status) {
      if (!this.selectedCars.length) return
      
      const actionText = status === 1 ? '上架' : '下架'
      
      try {
        await this.$confirm(`确认要批量${actionText}选中的车辆吗？`, '提示', {
          type: 'warning'
        })
        
        const cids = this.selectedCars.map(car => car.cid).join(',')
        const res = await request.get('/CarBatchStatusServlet', {
          params: {
            cids,
            status
          }
        })
        
        if (res.code === 0) {
          this.$message.success(`批量${actionText}成功`)
          this.fetchData()
        } else {
          this.$message.error(res.msg || `批量${actionText}失败`)
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error(`批量${actionText}失败:`, error)
          this.$message.error(`批量${actionText}失败`)
        }
      }
    },

    // 处理每页显示数量变化
    handleSizeChange(val) {
      this.pagination.pageSize = val
      this.pagination.currentPage = 1 // 重置到第一页
    },
    
    // 处理页码变化
    handleCurrentChange(val) {
      this.pagination.currentPage = val
    }
  }
}
</script>

<style lang="less" scoped>
.car-list {
  .search-card {
    margin-bottom: 20px;
  }

  .operation-bar {
    margin-bottom: 20px;
    
    .el-button {
      margin-right: 10px;
    }
  }

  .pagination-container {
    margin-top: 20px;
    text-align: right;
  }
}
</style> 